<template>
  <div class="search-container">
    <!-- action="/" 使ios键盘的发送按钮 变为搜索按钮  -->
    <van-sticky>
      <form action="/">
        <van-search
          v-model.trim="searchText"
          show-action
          placeholder="请输入搜索关键词"
          background="#3296fa"
          @search="onSearch"
          @cancel="$router.back()"
          @focus="isShowResults = false"
        />
      </form>
    </van-sticky>

    <!-- 搜索结果 -->
    <SearchResults :searchText="searchText" v-if="isShowResults"/>
    <!-- 搜索历史 -->
    <SearchHistory @clear-history="history = []" @search="onSearch" :history="history" v-else-if="!searchText" />
    <!-- 联想建议 -->
    <SearchSuggestion @clickItem="onSearch" :searchText="searchText" v-else />
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResults from './components/search-results'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  data () {
    return {
      searchText: '',
      isShowResults: false,
      history: getItem('HMTT-HISTORY') || [] // 记录搜索历史
    }
  },

  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResults
  },

  watch: {
    history: {
      deep: true, // 开启深度监听
      handler () {
        setItem('HMTT-HISTORY', this.history)
      }
    }
  },

  created () {

  },

  methods: {
    // 敲回车或者点击搜索
    onSearch (val) {
      if (val === '') return
      // 记录搜索历史
      this.history.unshift(val)
      // es6 新方法 可以实现数据去重
      this.history = [...new Set(this.history)]
      this.searchText = val
      this.isShowResults = true
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
